package ldu.guofeng.imdemo.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;

public class FileUtils {
	private static final String OBJECT_PERSISTANCE_DIR = "obj";

	public static boolean saveObjectToFile(Context ctx, String fileName, Object obj) {
		try {
			ByteArrayOutputStream mem_out = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(mem_out);
			out.writeObject(obj);
			out.close();
			String absolutePath = ctx.getFilesDir().getAbsolutePath() + OBJECT_PERSISTANCE_DIR;
			File path = new File(absolutePath);
			if (!path.exists()) {
				path.mkdirs();
			}
			FileOutputStream fs = new FileOutputStream(new File(path.getAbsolutePath() + File.separator + fileName));
			fs.write(mem_out.toByteArray());
			mem_out.close();
			fs.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public static Object readObjectFromFile(Context ctx, String fileName) {
		try {
			String absolutePath = ctx.getFilesDir().getAbsolutePath() + OBJECT_PERSISTANCE_DIR;
			File f = new File(absolutePath);
			if (!f.exists()) {
				f.mkdirs();
				return null;
			}
			FileInputStream is = new FileInputStream(new File(f.getAbsolutePath() + File.separator + fileName));
			ObjectInputStream in = new ObjectInputStream(is);
			Object object = null;
			try {
				object = in.readObject();
			} catch (ClassNotFoundException e) {
				// not found;
			}
			in.close();
			is.close();
			return object;
		} catch (Exception e) {
			return null;
		}
	}
}
